using System;
using System.Text.RegularExpressions;
using Gtk;

namespace Sqlpager
{
	public static class Util 
	{
		public static string SqlDate(DateTime date)
        {
            if (date == DateTime.MinValue)
                return null;
            return date.ToString("yyyy-MM-dd");
        }		
        
		public static bool IsDate(string date)
		{
			return (CDate(date)!=DateTime.MinValue);	
		}
		
		public static string Cut(string text,int digits)
		{
			return 
				(text.Length > digits)?
					text.Substring(0,digits)+"...":
					text;
		}
		
		public static string Md5(string Value)
		{
		        System.Security.Cryptography.MD5CryptoServiceProvider x = 
				   new System.Security.Cryptography.MD5CryptoServiceProvider();
		        byte[] data = System.Text.Encoding.ASCII.GetBytes(Value);
		        data = x.ComputeHash(data);
		        string ret = "";
		        for (int i=0; i < data.Length; i++)
				ret += data[i].ToString("x2").ToLower();
		        return ret;
		}
		
		public static bool IsIpAddress(string ip)
		{
			return Regex.IsMatch(ip,
			@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
				
		}
		
		public static bool IsEmail(string email)
		{
			if(Regex.IsMatch(email,@"^[a-z0-9.-]+@[a-z0-9.-]+\.[a-z]{2,4}$"))				
				return true;
			return false;
		}
		
		public static double CDouble(object obj)
		{
			double result = 0.0;
			try{
				result = Double.Parse("0"+obj);
			}catch{}
			return result;
		}
		
		public static int CInt(object obj)
		{
			int result = 0;
            try {
            	result = Int32.Parse("0"+obj);
            } catch { }            
			return result;
		}
        
		public static DateTime CDate(object obj)
        {
            DateTime result = DateTime.MinValue;
            try {
               	result = Convert.ToDateTime(obj.ToString());
            } catch { }
            return result;
        }      
        public static bool CBool(object obj)
        {
            bool result = false;
            try {
           		result = Convert.ToBoolean(obj);
            } catch { }
            return result;
        }
		
	}
}
